package com.ahies.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.micrometer.core.instrument.util.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: Mr.Yu
 * @Date: 2020/12/01
 * @Description: 登陆过滤器
 */
@Component
public class LoginFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 登陆过滤器优先级应为在限流过滤器之后
     * @return
     */
    @Override
    public int filterOrder() {
        return FilterConstants.SERVLET_DETECTION_FILTER_ORDER - 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }


    @Override
    public Object run() throws ZuulException {
        //获取zuul提供的上下文对象
        RequestContext context = RequestContext.getCurrentContext();
        //从上下文对象中获取请求对象
        HttpServletRequest request = context.getRequest();
        //获取token信息
        //String token = request.getParameter("token");
        String token = request.getHeader("token");
        if("/backend/list".equals(request.getRequestURI())){
            System.out.println("放行");
            return null;
        }

        //判断
        if(StringUtils.isBlank(token)){
            //获取改请求，不对其进行路由过滤
            context.setSendZuulResponse(false);
            //设置响应状态码为，401
            context.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
            //设置响应信息
            context.setResponseBody("{\"status\":\"401\",\"text\":\"no login!\"}");
        }
        context.set("token",token);
        return null;
    }

}
